﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataAccessLayer;
using Common;
using DataAccessLayer.DAL;
using System.Net.Mail;
using System.IO;
using System.Threading;

namespace BestBuy.Account
{
    public partial class Register : System.Web.UI.Page
    {

        private static readonly string ActiveEmailTemplate = "~/EmailTemplates/ActiveUser{0}.htm";

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void CreateUserButton_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }
            int userType = BuyerAccountType.Checked ? (int)RoleType.Buyer : (int)RoleType.Seller;

            string activeCode = Guid.NewGuid().ToString();
            DataAccessLayer.User user = new DataAccessLayer.User()
            {
                FirstName = FirstName.Text.Trim(),
                LastName = LastName.Text.Trim(),
                RoleID = userType,
                Email = Email.Text.Trim(),
                PhoneNumber = PhoneNumber.Text.Trim(),
                Username = UserName.Text.Trim(),
                Password = Password.Text,
                Status = (int)UserStatus.Inactive,
                GoldMemberDueTo = DateTime.Today,
                ActiveCode = activeCode,
            };

            UserDAL.CreateUser(user);

            // Send verification email

            Thread sendmailThread = new Thread(delegate()
            {
                SendEmail(user.Email, user.FirstName + " " + user.LastName, user.ActiveCode);
            });
            sendmailThread.IsBackground = true;
            sendmailThread.Start();

            Response.Redirect("~/Account/RegisterSuccess.aspx?UserID=" + user.ID);
        }

        /// <summary>
        /// Get Email Template Path function
        /// </summary>
        /// <returns></returns>
        private string GetEmailTemplatePath()
        {
            string path = ActiveEmailTemplate;

            // Current support Vietnamese
            path = string.Format(path, "");
            return path;
        }

        /// <summary>
        /// Send email methods
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="passWord"></param>
        /// <returns></returns>
        private void SendEmail(string emailAdds, string fullname, string code)
        {
            try
            {
                string subject = "Kích hoạt tài khoản tại BestBuy";

                string activeLink = string.Format("{0}/Account/ActiveUser.aspx", System.Configuration.ConfigurationManager.AppSettings["HOST_URI"]);
                activeLink += string.Format("?Code={0}", code);

                MailMessage mailMsg = new MailMessage();

                mailMsg.Subject = subject;
                mailMsg.To.Add(emailAdds);
                mailMsg.IsBodyHtml = true;
                string htmlBody = File.ReadAllText(Server.MapPath(GetEmailTemplatePath()));
                mailMsg.Body = htmlBody.Replace("{fullname}", fullname)
                                       .Replace("{activelink}", activeLink);

                SmtpClient smtp = new SmtpClient();
                smtp.Send(mailMsg);
            }
            catch
            {

            }
            
        }

        protected void EmailExistedValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            var user = UserDAL.GetUserByEmail(Email.Text.Trim());
            args.IsValid = user == null;
        }

        protected void UsernameExistedValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            var user = UserDAL.GetUserByUsername(UserName.Text.Trim());
            args.IsValid = user == null;
        }
    }
}
